<template>
  <!-- <div class="app-container home" style="margin-top: -15px;"> -->
    <div>
    <IndexPage :sysFirstList="sysFirstList" @handleUpdate="handleUpdate" ></IndexPage>
    <el-dialog :title="title" :visible.sync="openCity" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="城市" prop="city">
      <el-select v-model="form.city" placeholder="请选择城市" @change="onCityChange">
        <el-option v-for="city in cities" :key="city.id" :label="city.name" :value="city.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="地区" prop="region">
      <el-select v-model="form.region" placeholder="请选择地区" :disabled="!form.city">
        <el-option v-for="region in regions" :key="region.id" :label="region.name" :value="region.name"></el-option>
      </el-select>
    </el-form-item>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-input v-model="form.id" prop="id" v-if="false" />
      <el-form-item label="背景图片"  required>
      <el-upload  :limit="1" accept=".jpg,.png"  v-model="form.imageUrl"
       ref="uploadPic"
      :headers="upload.headers" 
      :action="upload.url + '?valueId=' + form.id + '&fileType=pic' " 
      :disabled="upload.isUploading" 
      :on-progress="handleFileUploadProgress" 
      :on-success="handleImageSuccess" 
      :before-upload="beforeImageUpload" 
      :auto-upload="true">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <span style="color: red;">支持上传图片,仅允许jpg/png格式文件</span>

          <el-form-item label="视频文件"  required>
      <el-upload  :limit="1" accept=".mp4,.avi,.rmvb" v-model="form.videoUrl"
       ref="uploadVideo"
      :headers="upload.headers" 
      :action="upload.url + '?valueId=' + form.id+ '&fileType=video' " 
      :disabled="upload.isUploading" 
      :on-progress="handleFileUploadProgress" 
      :on-success="handleVideoSuccess" 
      :auto-upload="true">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <span style="color: red;">支持上传视频文件,仅允许mp4/avi/rmvb格式文件</span>

        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPicAndHotelFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>





          <el-dialog :title="uploadHotel.title" :visible.sync="uploadHotel.open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-input v-model="form.id" prop="id" v-if="false" />
      <el-form-item label="视频文件" prop="uploadFile" required>
      <el-upload :limit="1" accept=".mp4,.avi,.rmvb"
       ref="uploadHotelVideo" 
      :headers="upload.headers" 
      :action="uploadHotel.url + '?valueId=' + form.id" 
      :disabled="upload.isUploading" 
      :on-progress="handleFileUploadProgress" 
      :on-success="handleFileSuccess" 
      :auto-upload="false">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <span style="color: red;">支持上传视频文件,仅允许mp4/avi/rmvb格式文件。</span>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="uploadHotel.open = false">取 消</el-button>
      </div>
    </el-dialog>

      <el-dialog :title="uploadBack.title" :visible.sync="uploadBack.open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="背景样式" prop="value2" required>
          <el-select v-model="form.value2" style="width: 280px;">
                <el-option v-for="(item, index) in firstBackImgOrColor" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="背景颜色" prop="value3" required v-if="form.value2 == 0">
          <!-- <el-input v-model="form.value3" placeholder="请输入颜色关键字"  /> -->
          <el-color-picker v-model="form.value3" placeholder="请选择颜色" show-alpha />
        </el-form-item>
      <el-input v-model="form.id" prop="id" v-if="false"  />
      <el-form-item label="背景图片" prop="uploadFile" required v-if="form.value2 == 1">
      <el-upload ref="uploadBack" :limit="1" accept=".jpg,.png," 
      :headers="uploadBack.headers" 
      :action="uploadBack.url + '?valueId=' + form.id" 
      :disabled="uploadBack.isUploading" 
      :on-progress="handleFileUploadBackProgress" 
      :on-success="handleFileBackSuccess" 
      :auto-upload="false">
      <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
    </el-form-item>
    <span>支持导入图片,仅允许jpg/png格式文件。</span>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileBackForm">确 定</el-button>
        <el-button @click="uploadBack.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openDes" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="酒店描述" prop="description">
          <el-input v-model="form.description" type="textarea"  placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="配置说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSysFirst, getSysFirst, delSysFirst, addSysFirst, updateSysFirst , updatePicOrVideo } from "@/api/system/sysFirst";
import axios from "axios";
import { getToken } from "@/utils/auth";
import IndexPage from './indexPage.vue'

export default {
  name: "SysFirst",
  components: { IndexPage },
  data() {
    return {
      // 遮罩层
      loading: true,
      getCitiesUrl: process.env.VUE_APP_BASE_API + "/system/sysFirst/getCities", // 获取所有城市
      getRegionsUrl: process.env.VUE_APP_BASE_API + "/system/sysFirst/getRegions", // 获取所有地区
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 终端首页配置表格数据
      sysFirstList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openPic: false,
      openCity: false,
      openDes: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        key: null,
        value1: null,
        value2: null,
        value3: null,
        value4: null,
        description: null,
      },
      isHotelRow:true,
      // 表单参数
      form: {
        city: '',
        region: '',
        imageUrl: '',
        videoUrl: '',
        remark: ''
      },
      // 表单校验
      rules: {
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        region: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        value3: [
          { required: true, message: '背景颜色不允许为空', trigger: "blur"}
        ]
      },
      cities: [],
      regions: [],
      // 目标裁剪尺寸，可根据需求修改
      targetWidth: 258,   // 目标宽度
      targetHeight: 164,  // 目标高度
      // 文件导入参数
      upload: {
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        //url: process.env.VUE_APP_BASE_API + "/system/sysFirst/uploadPicAndVideoFile",
        url: process.env.VUE_APP_BASE_API + "/common/uploadToUrl",
      },
      uploadHotel: {
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        url: process.env.VUE_APP_BASE_API + "/system/sysFirst/uploadHotelVideoFile",
      },
      //背景颜色设置
      uploadBack:{
        // 是否显示弹出层（文件导入）
        open: false,
        // 弹出层标题（文件导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/sysFirst/uploadBackFile"
      },
      firstBackImgOrColor: [{
        "label": "图片",
        "value": "1"
      }, {
        "label": "颜色",
        "value": "0"
      }]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询终端首页配置列表 */
    getList() {
      this.loading = true;
      listSysFirst(this.queryParams).then(response => {
        this.sysFirstList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openCity = false;
      this.openDes = false;
      this.openPic = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        keyId: null,
        value1: null,
        value2: null,
        value3: null,
        value4: null,
        imageUrl: null,
        videoUrl: null,
        description: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加终端首页配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      console.log("修改ID:"+id);
      getSysFirst(id).then(response => {
        this.form = response.data;
        // this.open = true;
        if(id == 1){
          this.openCity = true;
          this.fetchCities();
        }else if(id == 2){
          this.openDes = true;
        }else if(id == 7){
          if (this.$refs.uploadBack) {
            this.$refs.uploadBack.clearFiles(); // 清空背景图文件列表
          }
          this.uploadBack.open = true;
        }else if(id == 8){
          if (this.$refs.uploadHotelVideo) {
            this.$refs.uploadHotelVideo.clearFiles(); // 清空背景图文件列表
          }
          this.uploadHotel.open = true;
          this.uploadHotel.title = "企业介绍视频上传";
        }else{
          // this.openPic =true;
          if (this.$refs.uploadPic) {
            this.$refs.uploadPic.clearFiles(); // 清空背景图文件列表
          }
          if (this.$refs.uploadVideo) {
            this.$refs.uploadVideo.clearFiles(); // 清空背景图文件列表
          }
          this.upload.open=true;
          console.log("============="+JSON.stringify(this.form));
        }

        this.title = "终端首页配置";
      });
    },

    async fetchCities() {
      try {
        // const response = await axios.get('/api/cities'); // 替换为实际的获取城市的接口地址
        // this.cities = response.data;
        const token = getToken();
      axios.get(this.getCitiesUrl,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.cities = response.data.data;
          // console.log("获取到城市:"+JSON.stringify(this.cities));
        });
      } catch (error) {
        console.error('获取城市数据失败:', error);
      }
    },
    async onCityChange(cityValue) {
      if (cityValue) {
        this.form.region = ''; // 清空地区选择
        try {
          // const response = await axios.get(`/api/regions?city=${cityValue}`); // 替换为实际的获取地区的接口地址
          // this.regions = response.data;
          // this.form.region = ''; // 清空地区选择
          const token = getToken();
      axios.get(this.getRegionsUrl+"?city="+cityValue,{
        headers: {
          'Authorization': `Bearer `+token, // 假设 token 是你获取到的认证令牌
        },
      })
        .then(response => {
          this.regions = response.data.data;
          // this.form.region = ''; // 清空地区选择
        });
        } catch (error) {
          console.error('获取地区数据失败:', error);
        }
      } else {
        this.regions = [];
        this.form.region = '';
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSysFirst(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.openCity = false;
              this.openDes = false;
              this.openPic = false;
              this.uploadBack.open = false;
              this.getList();
            });
          } else {
            addSysFirst(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },




    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除终端首页配置编号为"' + ids + '"的数据项？').then(function() {
        return delSysFirst(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sysFirst/export', {
        ...this.queryParams
      }, `sysFirst_${new Date().getTime()}.xlsx`)
    },
        // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileUploadBackProgress(event, file, fileList) {
      this.uploadBack.isUploading = true;
    },
    handleFileBackSuccess(response, file, fileList) {
      this.uploadBack.open = false;
      this.uploadBack.isUploading = false;
      this.$refs.uploadBack.clearFiles();
      this.getList();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.uploadHotel.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.getList();
    },

    handleImageSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      console.log("======图片:"+JSON.stringify(response));
      this.form.imageUrl = response.fileName; // 假设接口返回文件URL
      this.$message.success('背景图片上传成功');
    },
    
    // 处理视频上传成功
    handleVideoSuccess(response, file, fileList) {
      this.upload.isUploading = false;
            console.log("======视频:"+JSON.stringify(response));
      this.form.videoUrl = response.fileName; // 假设接口返回文件URL
      this.$message.success('视频文件上传成功');
    },

    submitPicAndHotelFileForm() {
       updatePicOrVideo(this.form).then(response => {
              this.$modal.msgSuccess("更新成功");
              this.upload.open = false;
              this.getList();
            });
    },

      // 保存表单数据（两个文件都上传成功后调用）
    saveFormData() {
      // 这里可以将图片和视频的URL等信息提交到后端保存
      console.log('表单数据', this.form);
      // 调用保存接口...
      this.$message.success('表单提交成功');
      this.upload.open = false;
    },
    // 提交上传文件
    submitFileForm() {
      const uploadFiles = this.$refs.uploadHotelVideo.uploadFiles;
      console.log("当前选择上传文件个数:"+uploadFiles.length);
        if (uploadFiles.length === 0) {
          this.$message.error('请选择要上传的文件');
          return;
        }
      this.$refs.uploadHotelVideo.submit();
    },
    submitFileBackForm() {
      console.log("点击确定按钮");
      if (this.form.value2 == 1) {
        console.log("图片");
        const uploadFiles = this.$refs.uploadBack.uploadFiles;
        console.log("文件个数:"+uploadFiles.length);
        if (uploadFiles.length === 0) {
          this.$message.error('请选择要上传背景图片');
          return;
        }
        this.$refs.uploadBack.submit();
      }else if (this.form.value2 == 0) {
        console.log("颜色");
        this.submitForm();
      }
      this.getList();
    },


        // 图片上传前处理
    beforeImageUpload(file) {
      // 只处理图片文件
      // const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      // if (!isImage) {
      //   this.$message.error('只能上传JPG/PNG格式的图片');
      //   return false;
      // }
      console.log("======================图片上传前处理============");
      // 返回Promise，用于异步处理裁剪
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const img = new Image();
          img.onload = () => {
            // 创建canvas进行裁剪
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // 设置canvas尺寸为目标尺寸
            canvas.width = this.targetWidth;
            canvas.height = this.targetHeight;
            
            // 绘制图片并裁剪
            // 这里使用了等比例缩放并居中裁剪的策略
            const scale = Math.max(
              this.targetWidth / img.width,
              this.targetHeight / img.height
            );
            const x = (this.targetWidth - img.width * scale) / 2;
            const y = (this.targetHeight - img.height * scale) / 2;
            
            ctx.drawImage(
              img,
              0, 0, img.width, img.height,
              x, y, img.width * scale, img.height * scale
            );
            
            // 将canvas内容转为Blob对象
            canvas.toBlob((blob) => {
              // 创建新的文件对象，保持原文件名称和类型
              const croppedFile = new File(
                [blob],
                file.name,
                { type: file.type, lastModified: Date.now() }
              );
              
              // 替换原文件进行上传
              resolve(croppedFile);
            }, file.type);
          };
          img.src = e.target.result;
        };
        reader.readAsDataURL(file);
      });
    },





  }
};
</script>
